﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EzDesk.DesktopClient.ViewModel
{
    using EzDesk.DesktopClient.ViewContract;
    using EzDesk.MVVMBase;
    using EzDesk.DesktopClient.Model;
    using EzDesk.EventAggregation;
    using EzDesk.DesktopClient.Event;
    using EzDesk.Generic;
    using EzDesk.DesktopClient.MVVMEnhance;

    public class LoginViewModel : ViewModelWithSingleContainer<ILoginView>, ILoginViewModel
    {

        #region Fields
        private LoginEvent _loginEvent = EventAggregator<LoginEvent>.GetEvent();
        private UserManagement _userManagement;
        private bool _isLoging = false;
        private string _errorMessage;
        #endregion Fields
        #region Properties
    
        public bool IsViewEnable
        {
            get
            {
                return !_isLoging;
            }
            set
            {
                _isLoging = !value;
                RaisePropertyChanged("IsViewEnable");
            }
        }

        public string PasswordLink
        {
            get
            {
                return "http://www.g.cn";
            }
        }

        public string ErrorMessage
        {
            get { return _errorMessage; }
            set
            {
                _errorMessage = value;
                RaisePropertyChanged("ErrorMessage");
            }
        }

        #endregion Properties
        #region Constructor
        public LoginViewModel():base()
        {
            InitField();
            InitEvent();
        }
        private void InitField()
        {
            _userManagement = UserManagement.Instance;
        }
        private void InitEvent()
        {
            InitGlobalEvent();
        }

        private void InitGlobalEvent()
        {
            _loginEvent.Subscribe(this.LoginFinished);
            LoginFailedEvent.Instance.Subscribe(this.LoginFailed);
        }

        #endregion Constructor

        public void Login(string userName, string password)
        {
            IsViewEnable = false;
            _userManagement.Login(userName, password);

        }

        void LoginFinished(LoginArgs loginArgs)
        {
            IsViewEnable = true;
        }
        void LoginFailed(LoginFailedArgs args)
        {
            IsViewEnable = true;
            ErrorMessage = args.Information;
            View.LoginFailed();
        }
    }
}
